import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { Observable } from "rxjs";
import { Reflector } from "@nestjs/core";
// import { RolesService } from "./roles.service";
import { RoleService } from 'src/role/role.service';
import { ObjectId } from "mongodb";

@Injectable()
export class RolesGuard implements CanActivate {
    constructor(private reflector: Reflector, private roleService: RoleService) { }

    async canActivate(context: ExecutionContext): Promise<boolean> {
        const roles = this.reflector.get<string[]>("roles", context.getHandler());
        console.log("#### roles", roles);
        if (!roles) {
            return true;
        }

        const request = context.switchToHttp().getRequest();
        const user = request.user; // 从请求中获取用户信息

        console.log("### user", user);
        let ids = user.roles;
        console.log(ids, typeof ids[0]);

        let list: any[] = await this.roleService.findMany(ids);
        console.log(list);
        list = list.map(i => i.name);
        let enable = list.some(item => roles.includes(item));
        console.log("enable", enable);

        // 检查用户角色是否包含在指定的角色数组中或与请求的用户ID匹配
        if (enable || user.id === request.params.id) {
            return true;
        }

        return false;
    }
}